<template>
  <div id="roleAdmin">
    <template>
      <!--显示信息-->
      <el-table
          ref="multipleTable"
          :data="filte.slice((currPage-1)*pageSize,currPage*pageSize)"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            prop="name"
            label="角色名称"
            width="120">
        </el-table-column>
        <el-table-column
            prop="auth"
            label="权限描述"
            width="120"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            prop="description"
            label="具体描述"
            width="120"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            prop="date"
            label="创建时间"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            align="right">
          <template slot="header">
            <el-input
                v-model="search"
                size="mini"
                placeholder="输入角色名搜索"/>
          </template>
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="viewDetail(scope.$index,scope.row)">编辑
            </el-button>
            <el-button
                size="mini"
                type="danger"
                @click="del(scope.$index)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--            分页-->
      <el-pagination
          class="pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currPage"
          :page-sizes="[5,10,20,50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filte.length">
      </el-pagination>
      <div style="margin-top: 20px">
        <el-button type="primary" @click="AddRole">新增角色</el-button>
        <el-button type="danger" @click="del()">批量删除</el-button>
      </div>
    </template>

    <!--编辑页面-->
    <el-dialog title="角色编辑" width="920px" :before-close="clo" class="dialog dialogAdd"
               custom-class="custom-dialog"
               :visible.sync="dialogEditVisible" :close-on-click-modal='false'>
      <el-form ref="editForm" style="margin-right: 20px;" :model="editForm" :inline="true" label-position="right"
               label-width="110px" size="mini">
        <el-form-item label="角色名称" prop="khxm">
          <el-input v-model="editForm.name" :disabled="!isEdit || editForm.opnId"></el-input>
        </el-form-item>
        <el-form-item label="权限描述" prop="remark">
          <el-input v-model="editForm.auth" :disabled="!isEdit"></el-input>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-input v-model="editForm.date" disabled></el-input>
        </el-form-item>
        <el-form-item label="具体描述" prop="remark">
          <el-input v-model="editForm.description" :disabled="!isEdit"></el-input>
        </el-form-item>
        <!--角色全选复选框组件-->
        <role-table @getPath="getPath" :isEdit="isEdit" :editForm="editForm" :role="role"/>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="editForm.state != 3">
        <el-button v-if="!isEdit" @click="formEdit" size="mini">编 辑</el-button>
        <el-button v-else @click="cancelEdit" size="mini">取消编辑</el-button>
        <el-button type="primary" @click="saveEdit" size="mini">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import role from '../../js/admin/role'
import roleTable from "../../components/admin/roleTable";

export default {
  name: "roleAdmin",
  components: {
    roleTable,
  },
  data() {
    return {
      tableData: JSON.parse(localStorage.getItem('roleArr')),
      search: '',
      multipleSelection: [],
      editForm: {}, // 新增表单
      editFromClone: {},
      sub: '',
      isEdit: false,   // 是否编辑
      dialogEditVisible: false,  // 新增模态框
      role,
      Add: false,
      currentPage1: 1,
      currPage: 1,
      pageSize: 5,
    }
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    del(index) {
      this.$confirm('此操作将永久删除该角色 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableData = this.tableData.filter(item => {
          if (this.multipleSelection.indexOf(item) == -1) {
            return item;
          }
        })
        if (index || index == 0) this.tableData.splice(index, 1);
        localStorage.setItem('roleArr', JSON.stringify(this.tableData))
        for (let i = 0; i < this.multipleSelection.length+1; i++) {
          this.delEmploy();
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    viewDetail(index, row) {
      this.editFromClone = this.deepClone(row)
      this.editForm = row
      this.sub = index
      this.dialogEditVisible = true
      this.Add = false
    },
    AddRole() {
      this.Add = true;
      this.sub = '',
          this.editForm = {
            role: [],
            date: function () {
              let date = new Date();
              let newdate = date.getFullYear() + '年' + (date.getMonth() + 1) + '月' + date.getDate() + '日';
              return newdate
            }(),
          };

      this.dialogEditVisible = true
    },
    // 保存编辑
    saveEdit() {
      if ((this.editForm.name) && (this.editForm.role.length > 0)) {
        this.set(this.editForm);
        this.updateEmploy();
        this.dialogEditVisible = false
        this.isEdit = false;
        this.sub = '';
      } else if (this.Add) {
        this.$confirm('姓名或者权限不能为空，是否继续新增', '提示', {
          confirmButtonText: '继续',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: '继续新增!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消新增'
          });
          this.isEdit = false;
          this.dialogEditVisible = false
        });
      } else {
        this.$confirm('姓名或者权限不能为空，是否继续新修改', '提示', {
          confirmButtonText: '继续',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: '继续修改!'
          });
        }).catch(() => {
          this.tableData.splice([this.sub], 1, this.editForm);
          this.dialogEditVisible = false
          this.isEdit = false;
          console.log(this.tableData[this.sub])
          this.$message({
            type: 'info',
            message: '取消修改'
          });
        });
      }
    },

    formEdit() {
      this.isEdit = true;
    },
    // 取消编辑
    cancelEdit() {
      this.isEdit = false;

      console.log()
      if (this._.isNil(this.editFromClone)) {
        this.editForm = this.deepClone(this.editFromClone)
      }
    },
    getPath(temp) {
      this.editForm.role = temp.role;
    },
    set(arr) {
      if (this.sub || this.sub === 0) {
        this.tableData[this.sub] = arr;
        localStorage.setItem('roleArr', JSON.stringify(this.tableData))
      } else {
        this.tableData.push(arr);
        localStorage.setItem('roleArr', JSON.stringify(this.tableData))
      }
    },
    deepClone(target) {
      // 定义一个变量
      let result;
      // 如果当前需要深拷贝的是一个对象的话
      if (typeof target === 'object') {
        // 如果是一个数组的话
        if (Array.isArray(target)) {
          result = []; // 将result赋值为一个数组，并且执行遍历
          for (let i in target) {
            // 递归克隆数组中的每一项
            result.push(this.deepClone(target[i]))
          }
          // 判断如果当前的值是null的话；直接赋值为null
        } else if (target === null) {
          result = null;
          // 判断如果当前的值是一个RegExp对象的话，直接赋值
        } else if (target.constructor === RegExp) {
          result = target;
        } else {
          // 否则是普通对象，直接for in循环，递归赋值对象的所有值
          result = {};
          for (let i in target) {
            result[i] = this.deepClone(target[i]);
          }
        }
        // 如果不是对象的话，就是基本数据类型，那么直接赋值
      } else {
        result = target;
      }
      // 返回最终结果
      return result;
    },
    handleSizeChange(val) {
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      this.currPage = val;
    },
    clo(done) {
      if (this.isEdit) {
        this.$confirm('内容未保存，是否退出', '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning'
        }).then(() => {
          this.editFromClone = {};
          this.$message({
            type: 'info',
            message: '已取消保存'
          });
          if (this.sub > -1 && this.sub != '') {
            this.tableData.splice(this.sub, 1, this.editFromClone)
          }
          this.dialogEditVisible = false
          this.isEdit = false
          this.sub = '';
          this.checkedCities = [];
          return done()
        }).catch(() => {
          this.$message({
            type: 'success',
            message: '请继续编辑'
          });
          return done(false)
        });
      } else {
        this.editFromClone = {};
        this.dialogEditVisible = false
        this.isEdit = false
        this.sub = '';
        return done()
      }
    },
    updateEmploy(){
      let roleArr = JSON.parse(localStorage.getItem('roleArr'));
      let employ = JSON.parse(localStorage.getItem('employ'))
      for (let i = 0; i < roleArr.length; i++) {
        for (let j = 0; j <employ.length ; j++) {
          for (let k = 0; k <employ[j].role.length ; k++) {
            if (employ[j].role[k].name == roleArr[i].name) employ[j].role[k]=roleArr[i];
          }
        }
      }
      localStorage.setItem('employ',JSON.stringify(employ));
    },
    delEmploy(){
      let roleArr = JSON.parse(localStorage.getItem('roleArr'));
      let employ = JSON.parse(localStorage.getItem('employ'))
      console.log(this.multipleSelection.length)
      for (let j = 0; j <employ.length ; j++) {
          for (let k = 0; k <employ[j].role.length ; k++) {
            let count = false;
            for (let i = 0; i < roleArr.length ; i++) {
              if (employ[j].role[k].name == roleArr[i].name) count = true;
            }
            if (!count) employ[j].role.splice(k,1);
          }
        }
      localStorage.setItem('employ',JSON.stringify(employ));
    }
  },
  computed: {
    filte() {
      let tableData = this.tableData.filter(data => !this.search ||
          data.name.toLowerCase().includes(this.search.toLowerCase()))
      return tableData
    }
  }
}
</script>

<style scoped lang="less">
#roleAdmin {
  width: 100%;
  background-color: white;
  padding: 20px 30px;
  box-sizing: border-box;
}

.pagination {
  text-align: center;
  margin: 20px 0;
}
</style>